﻿/****************
 * Copyright 2016 Brian Tabone
 * Licensed under the Apache 2.0 License
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Program.cs
 * Main module for SelfMap
 * 9/10/2016
 */
using System;
using System.Configuration;
using System.Diagnostics;
using System.Reflection;
using IAO.Common.Interfaces.Networking;
using IAO.Common.Network;
using IAO.Common.Network.MessageControllers;
using IAO.Common.ServiceFramework;
using IAO.Common.ServiceFramework.RuntimeProperties;
using log4net;
using log4net.Config;
using SelfMap.DataAccessLayer;

[assembly: XmlConfigurator(Watch = true)]

namespace SelfMap
{
    internal class Program
    {
        private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private static Uri _endpoint;
        private static Stopwatch _uptime;
        private static PropertyManager _propertyManager;
        private static SelfMapDal _dal;

        private static void Main(string[] args)
        {
            if (log.IsInfoEnabled)
            {
                log.Info(
                    $"Starting {Assembly.GetExecutingAssembly().GetName().Name} {Assembly.GetExecutingAssembly().GetName().Version}");
            }
            _dal = new SelfMapDal(log);
            _propertyManager = PropertyManager.GetPropertyManager;
            _propertyManager.SetDataAccessLayer(_dal);
            _uptime = new Stopwatch();
            _uptime.Start();
            _endpoint = new Uri(ConfigurationManager.AppSettings["SelfMapEndpoint"]);

            _propertyManager.AddProperty(new VolatileProperty(1, "System", "Endpoint", _endpoint.ToString(), typeof(string).ToString(),
                true));
            _propertyManager.AddProperty(new VolatileProperty(2, "System", "Application", Assembly.GetExecutingAssembly().Location,
                typeof(string).ToString(), true));
            _propertyManager.AddProperty(new UptimeProperty(3));
            _propertyManager.AddPersistentPropertyIfNotExists(new TestProperty(4, "Test", "TestSetter", "NotYetSet", typeof(string).ToString(), false));
            _propertyManager.AddPersistentPropertyIfNotExists(new TestProperty(5, "Test", "TestIntSet", "0", typeof(int).ToString(), false));

            IMessageChannel msgChannel = new MessageChannel(_endpoint.Host, (ushort) _endpoint.Port);
            PropertiesController.GetPropertiesEvent +=
                PropertyManager.GetPropertyManager.PropertiesController_GetPropertiesEvent;
            PropertiesController.SetPropertiesEvent +=
                PropertyManager.GetPropertyManager.PropertiesController_SetPropertiesEvent;
            msgChannel.StartListening();

            Console.WriteLine($"Message Channel started on {msgChannel.Host}:{msgChannel.Port}");
            Console.WriteLine("Press enter to stop");
            Console.ReadLine();

            msgChannel.StopListening();
        }
    }
}